package controllers

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"helloCms/models"
	"time"
	"path"
	"os"
)

type ActionController struct {
	beego.Controller
}

func (c *ActionController)Index()  {
	c.TplName="ActionInfo/Index.html"
}

func (c *ActionController)GetActionInfo()  {
	pageIndex,_:=c.GetInt("page")
	pageSize,_:=c.GetInt("rows")
	start:=(pageIndex-1)*pageSize

	o:=orm.NewOrm()
	actions:=make([]models.Actioninfo,0)
	o.QueryTable("Actioninfo").Filter("del_flag",0).OrderBy("Id").Limit(pageSize,start).All(&actions)
	count,_:=o.QueryTable("Actioninfo").Filter("del_flag",0).Count()

	c.Data["json"]=map[string]interface{}{"rows":actions,"total":count}
	c.ServeJSON()
}



func (c *ActionController)FileUp()  {//上传图片
	f,h,err:=c.GetFile("fileUp")
	defer f.Close()
	if err!=nil{
		c.Data["json"]=map[string]interface{}{"flag":"no","msg":"文件上传失败"}
		c.ServeJSON()
		return
	}
	if path.Ext(h.Filename)!=".jpg" && path.Ext(h.Filename)!=".png"{
		c.Data["json"]=map[string]interface{}{"flag":"no","msg":"文件上传格式只支持jpg和png"}
		c.ServeJSON()
		return
	}
	if h.Size>5000000{
		c.Data["json"]=map[string]interface{}{"flag":"no","msg":"文件大小不得超过5M"}
		c.ServeJSON()
		return
	}
	dir:="./static/img/"+time.Now().Format("2006-01-02")+"/"
	_,err1:=os.Stat(dir)
	if err1!=nil{//表示没有文件夹。
		os.MkdirAll(dir,os.ModePerm) //和Mkdir区别是这个可以创建多个目录
	}
	fileName:=time.Now().Format("15h04m05s.000ms")//史前巨坑：windows文件名不能有冒号
	fullDir:=dir+fileName+path.Ext(h.Filename)
	//beego.Info(fullDir)
	//_, _, err= c.Ctx.Request.FormFile(fullDir)
	//if err != nil {
	//	beego.Info(err)
	//}
	err2:=c.SaveToFile("fileUp",fullDir)
	if err2!=nil{
		c.Data["json"]=map[string]interface{}{"flag":"no","msg":"文件保存失败"}
		c.ServeJSON()
		return
	}

	c.Data["json"]=map[string]interface{}{"flag":"ok","msg":fullDir}
	c.ServeJSON()
}

func (c *ActionController)AddAction()  {
	ActionTypeEnum,_:=c.GetInt("ActionTypeEnum")
	actioninfo:=models.Actioninfo{
		ActionInfoName:c.GetString("ActionInfoName"),
		ActionTypeEnum:ActionTypeEnum,
		MenuIcon:c.GetString("MenuIcon"),
		IconWidth:0,
		IconHeight:0,
		HttpMethod:c.GetString("HttpMethod"),
		Url:c.GetString("Url"),
		Remark:c.GetString("Remark"),
		DelFlag:0,
		AddDate:time.Now(),
		ModifDate:time.Now(),
	}
	o:=orm.NewOrm()
	_,err:=o.Insert(&actioninfo)
if err !=nil{
	c.Data["json"]=map[string]interface{}{"flag":"no"}
}
	c.Data["json"]=map[string]interface{}{"flag":"ok"}
	c.ServeJSON()
}